package com.runa.monitor.platinterface.extend.third.service.impl;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.constants.ResultConstants;
import com.runa.monitor.comm.dto.newComm.AsynResult;
import com.runa.monitor.comm.dto.newComm.HotMeterVO;
import com.runa.monitor.comm.dto.newComm.PanelVO;
import com.runa.monitor.comm.dto.newComm.ValveVO;
import com.runa.monitor.comm.entity.*;
import com.runa.monitor.platinterface.base.BaseContainer;
import com.runa.monitor.platinterface.extend.third.newester.pojo.NetEquDockingDataVo;
import com.runa.monitor.platinterface.extend.third.pojo.Result;
import com.runa.monitor.platinterface.extend.third.pojo.ResultCode;
import com.runa.monitor.platinterface.extend.third.pojo.TemperaturePressureCurrentData;
import com.runa.monitor.platinterface.extend.third.service.IThirdPartOfMeterService;
import com.runa.monitor.platinterface.extend.third.vo.*;
import com.runa.monitor.platinterface.mqtt.MqttUtil;
import com.runa.monitor.platinterface.platService.RepositoryService;
import com.runa.persistence.SerializeUtil;
import com.runa.persistence.repository.CommPanelRepository;
import com.runa.protocol.util.UtilTime;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Example;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@EnableScheduling
public class ThirdPartOfMeterServiceImpl implements IThirdPartOfMeterService {
    private static final String successCode = "0";
    private static final String errorCode = "-1";
    private static final String objectNotExist = "50000";
    
    @Resource
    private RepositoryService repositoryService;

    @Resource
    private CommPanelRepository commPanelRepository;

    @Override
    public Result<List<DockingDataResponseVo>> batchSaveHouseMeterData(List<HouseMeterDockingDataVo> houseMeterDockingDataVos) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(houseMeterDockingDataVos)) {
            for (HouseMeterDockingDataVo houseMeterDockingDataVo : houseMeterDockingDataVos) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                CommNetEquipment commNetEquipment = repositoryService.getCommNetEquipmentByNetSerial(houseMeterDockingDataVo.getNetEquSerialNo());
                if (check(responseVoList, dockingDataResponseVo, commNetEquipment, houseMeterDockingDataVo.getNetEquSerialNo()))
                    continue;
                CommMeter commMeter = repositoryService.getCommMeterByNodeSerialForNetEqu(houseMeterDockingDataVo.getSerialNo(), commNetEquipment.getId());
                if (commMeter == null) {
                    log.error("batchSaveHouseMeterData无数据库数据:" + JSON.toJSONString(houseMeterDockingDataVos));
                    dockingDataResponseVo.setNetEquSerialNo(houseMeterDockingDataVo.getNetEquSerialNo());
                    dockingDataResponseVo.setMeterSerialNo(houseMeterDockingDataVo.getSerialNo());
                    dockingDataResponseVo.setFieldCode(objectNotExist);
                    dockingDataResponseVo.setReason("节点设备档案不存在");
                    responseVoList.add(dockingDataResponseVo);
                    continue;
                }
                HotMeterVO hotMeterVO = new HotMeterVO();
                hotMeterVO.setMeterSerial(houseMeterDockingDataVo.getSerialNo());
                hotMeterVO.setSuccess(houseMeterDockingDataVo.getState());
                hotMeterVO.setFaultCode(Collections.singletonList(houseMeterDockingDataVo.getReason()));
                hotMeterVO.setReadDate(houseMeterDockingDataVo.getReadTime());
                hotMeterVO.setMeterDate(houseMeterDockingDataVo.getEquTime());
                hotMeterVO.setFlow(houseMeterDockingDataVo.getFlow().floatValue());
                hotMeterVO.setPower(houseMeterDockingDataVo.getHeat().floatValue());
                hotMeterVO.setAccFlow(houseMeterDockingDataVo.getAccFlow().floatValue());
                hotMeterVO.setAccHeat(houseMeterDockingDataVo.getAccHeat().floatValue());
//                if (hotMeterVO.getAccFlow().intValue()==0 || hotMeterVO.getAccHeat().intValue()==0)
//                    hotMeterVO.setSuccess(false);
                hotMeterVO.setSupplyTemp(houseMeterDockingDataVo.getSupplyTemperature().floatValue());
                hotMeterVO.setReturnTemp(houseMeterDockingDataVo.getReturnTemperature().floatValue());
                if (houseMeterDockingDataVo.getWorkTime() != null)
                    hotMeterVO.setWorkTime(houseMeterDockingDataVo.getWorkTime().intValue());
//                hotMeterVO.set(houseMeterDockingDataVo.getBattery());
                hotMeterVO.setStatus(houseMeterDockingDataVo.getStateCode());

                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
                asynResult.setIdentity(commMeter.getId());
//                asynResult.setSymbol("data");
                asynResult.setContent(hotMeterVO);
                if (!hotMeterVO.getSuccess()) {
                    asynResult.unreadSetting();
                    asynResult.setContent(null);
                }
                MqttUtil.send(HotMeterVO.TOPIC, asynResult);
            }
        }
        return new Result<List<DockingDataResponseVo>>().handleSuccessResult(responseVoList);
    }

    private boolean check(List<DockingDataResponseVo> responseVoList, DockingDataResponseVo dockingDataResponseVo, List<String> collect, String serialNo, String netEquSerialNo) {
        if (!collect.contains(serialNo)) {
            dockingDataResponseVo.setNetEquSerialNo(netEquSerialNo);
            dockingDataResponseVo.setMeterSerialNo(serialNo);
            dockingDataResponseVo.setFieldCode(objectNotExist);
            dockingDataResponseVo.setReason("节点设备档案不存在");
            responseVoList.add(dockingDataResponseVo);
            return true;
        }
        return false;
    }

    @Override
    public Result<List<DockingDataResponseVo>> batchSaveHouseValveData(List<HouseValveDockingDataVo> houseValveDockingDataVos) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(houseValveDockingDataVos)) {
            for (HouseValveDockingDataVo houseValveDockingDataVo : houseValveDockingDataVos) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                CommNetEquipment commNetEquipment = repositoryService.getCommNetEquipmentByNetSerial(houseValveDockingDataVo.getNetEquSerialNo());
                if (check(responseVoList, dockingDataResponseVo, commNetEquipment, houseValveDockingDataVo.getNetEquSerialNo()))
                    continue;
                CommValve commValve = repositoryService.getCommValveByNodeSerialForNetEqu(houseValveDockingDataVo.getSerialNo(), commNetEquipment.getId());
                if (commValve == null) {
                    log.error("batchSaveHouseValveData无此档案---" + JSON.toJSONString(houseValveDockingDataVo));
                    dockingDataResponseVo.setNetEquSerialNo(houseValveDockingDataVo.getNetEquSerialNo());
                    dockingDataResponseVo.setMeterSerialNo(houseValveDockingDataVo.getSerialNo());
                    dockingDataResponseVo.setFieldCode(objectNotExist);
                    dockingDataResponseVo.setReason("节点设备档案不存在");
                    responseVoList.add(dockingDataResponseVo);
                    continue;
                }
//                List<String> collect = commNetEquipment.getCommValveList().stream().map(CommValve::getSerial).collect(Collectors.toList());
//                if (check(responseVoList, dockingDataResponseVo, collect, houseValveDockingDataVo.getSerialNo(), houseValveDockingDataVo.getNetEquSerialNo()))
//                    continue;
                ValveVO valveVO = new ValveVO();
                valveVO.setValveSerial(houseValveDockingDataVo.getSerialNo());
                valveVO.setSuccess(houseValveDockingDataVo.getState());
                valveVO.setFaultCode(houseValveDockingDataVo.getReason());
//                valveVO.setPlanTime(houseValveDockingDataVo.getPlanTime());
                valveVO.setReadTime(houseValveDockingDataVo.getReadTime());
                valveVO.setValveDate(houseValveDockingDataVo.getEquTime());
                valveVO.setOpenTime(houseValveDockingDataVo.getWorkTime().floatValue());
                valveVO.setStatus(houseValveDockingDataVo.getStateCode());
//                valveVO.setSettingTemperature(houseValveDockingDataVo.getSettingTemperature());
                valveVO.setTempLock(houseValveDockingDataVo.getLockTemperature());
//                valveVO.setTemperature(houseValveDockingDataVo.getTemperature());
//                valveVO.setRemainderHeat(houseValveDockingDataVo.getRemainderHeat());
//                valveVO.setControlType(houseValveDockingDataVo.getControlType());
//                valveVO.setSwitchState(houseValveDockingDataVo.getSwitchState());
                valveVO.setActOpen(houseValveDockingDataVo.getValveOpening().floatValue());
//                valveVO.setStateCode(houseValveDockingDataVo.getStateCode());
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
                asynResult.setIdentity(commValve.getId());
//                asynResult.setSymbol("data");
                asynResult.setContent(valveVO);
                MqttUtil.send(ValveVO.TOPIC, asynResult);
            }
        }
        return new Result<List<DockingDataResponseVo>>().handleSuccessResult(responseVoList);
    }

    private boolean check(List<DockingDataResponseVo> responseVoList, DockingDataResponseVo dockingDataResponseVo, CommNetEquipment commNetEquipment, String netEquSerialNo) {
        if (commNetEquipment == null) {
            dockingDataResponseVo.setNetEquSerialNo(netEquSerialNo);
            dockingDataResponseVo.setFieldCode(objectNotExist);
            dockingDataResponseVo.setReason("网络设备不存在");
            responseVoList.add(dockingDataResponseVo);
            return true;
        }
        return false;
    }

    @Override
    public Result<List<DockingDataResponseVo>> batchSaveTemperaturePanelData(List<TemperaturePanelDockingDataVo> temperaturePanelDockingDataVos) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(temperaturePanelDockingDataVos)) {
            for (TemperaturePanelDockingDataVo temperaturePanelDockingDataVo : temperaturePanelDockingDataVos) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                CommNetEquipment commNetEquipment = repositoryService.getCommNetEquipmentByNetSerial(temperaturePanelDockingDataVo.getNetEquSerialNo());
                if (check(responseVoList, dockingDataResponseVo, commNetEquipment, temperaturePanelDockingDataVo.getNetEquSerialNo()))
                    continue;
                CommPanel commPanel = repositoryService.getCommPanelByNodeSerialForNetEqu(temperaturePanelDockingDataVo.getSerialNo(), commNetEquipment.getId());
                if (commPanel == null) {
                    log.error("batchSaveTemperaturePanelData无此档案---" + JSON.toJSONString(temperaturePanelDockingDataVo));
                    dockingDataResponseVo.setNetEquSerialNo(temperaturePanelDockingDataVo.getNetEquSerialNo());
                    dockingDataResponseVo.setMeterSerialNo(temperaturePanelDockingDataVo.getSerialNo());
                    dockingDataResponseVo.setFieldCode(objectNotExist);
                    dockingDataResponseVo.setReason("节点设备档案不存在");
                    responseVoList.add(dockingDataResponseVo);
                    continue;
                }
//                List<String> collect = commNetEquipment.getCommPanelList().stream().map(CommPanel::getSerial).collect(Collectors.toList());
//                if (check(responseVoList, dockingDataResponseVo, collect, temperaturePanelDockingDataVo.getSerialNo(), temperaturePanelDockingDataVo.getNetEquSerialNo()))
//                    continue;
                PanelVO panelVO = new PanelVO();
                panelVO.setSerial(temperaturePanelDockingDataVo.getSerialNo());
                panelVO.setSuccess(temperaturePanelDockingDataVo.isState());
                panelVO.setFaultCode(temperaturePanelDockingDataVo.getReason());
//                panelVO.setPlanTime(temperaturePanelDockingDataVo.getPlanTime());
                panelVO.setReadTime(temperaturePanelDockingDataVo.getReadTime());
                panelVO.setPanelDate(temperaturePanelDockingDataVo.getEquTime());
                panelVO.setTemperature(temperaturePanelDockingDataVo.getTemperature().floatValue());
                panelVO.setStatus(temperaturePanelDockingDataVo.getStateCode());
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
                asynResult.setIdentity(temperaturePanelDockingDataVo.getNetEquSerialNo());
//                asynResult.setSymbol("data");
                asynResult.setContent(Collections.singleton(panelVO));
                MqttUtil.send(PanelVO.TOPIC, asynResult);
            }
        }
        return new Result<List<DockingDataResponseVo>>().handleSuccessResult(responseVoList);
    }

    @Override
    public Result<List<DockingDataResponseVo>> batchSaveTemperaturePressureData(List<TemperaturePressureDataDockingDataVo> temperaturePressureDataDockingDataVos) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(temperaturePressureDataDockingDataVos)) {
            for (TemperaturePressureDataDockingDataVo temperaturePressureDataDockingDataVo : temperaturePressureDataDockingDataVos) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                CommTemperaturepressure commTemperaturepressure = repositoryService.getCommTemperaturepressure(temperaturePressureDataDockingDataVo.getSerialNo());
                if (commTemperaturepressure == null) {
                    dockingDataResponseVo.setMeterSerialNo(temperaturePressureDataDockingDataVo.getSerialNo());
                    dockingDataResponseVo.setFieldCode(objectNotExist);
                    dockingDataResponseVo.setReason("温压监测仪不存在");
                    responseVoList.add(dockingDataResponseVo);
                    continue;
                }
                TemperaturePressureCurrentData currentData = new TemperaturePressureCurrentData();
                currentData.setSerial(temperaturePressureDataDockingDataVo.getSerialNo());
                currentData.setSuccess(temperaturePressureDataDockingDataVo.isState());
                currentData.setFaultCode(temperaturePressureDataDockingDataVo.getReason());
//                currentData.setPlanTime(temperaturePressureDataDockingDataVo.getPlanTime());
                currentData.setReadTime(temperaturePressureDataDockingDataVo.getReadTime());
                //供回温
                currentData.setSupplyTemp(temperaturePressureDataDockingDataVo.getSupplyTemperature().floatValue());
                currentData.setReturnTemp(temperaturePressureDataDockingDataVo.getReturnTemperature().floatValue());
                //供回压
                currentData.setSupplyPre(temperaturePressureDataDockingDataVo.getSupplyPressure().floatValue());
                currentData.setReturnPre(temperaturePressureDataDockingDataVo.getReturnPressure().floatValue());
                currentData.setStatus(temperaturePressureDataDockingDataVo.getStateCode());
                currentData.setBatteryVol(temperaturePressureDataDockingDataVo.getBatteryPressure().floatValue());
                currentData.setSignal(temperaturePressureDataDockingDataVo.getSignal());
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
//                asynResult.setSerial(temperaturePressureDataDockingDataVo.getNetEquSerialNo());
//                asynResult.setSymbol("data");
                asynResult.setContent(currentData);
                MqttUtil.send(TemperaturePressureCurrentData.TOPIC, asynResult);
            }
        }
        return new Result<List<DockingDataResponseVo>>().handleSuccessResult(responseVoList);
    }

    @Override
    public Result<List<DockingDataResponseVo>> batchSaveNetEquData(List<NetEquDockingDataVo> netEquDockingDataVos) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(netEquDockingDataVos)) {
            List<String> serialNos = netEquDockingDataVos.stream().map(NetEquDockingDataVo::getSerialNo).distinct().collect(Collectors.toList());
//            List<NetEqu> netEqus = netEquDao.findnetEquBySerialNos(serialNos);
//            repositoryService.getcommn
//            upService.updateBaseDataCache();
            for (NetEquDockingDataVo dockingDataVo : netEquDockingDataVos) {

                String serialNo = dockingDataVo.getSerialNo();
                Boolean state = dockingDataVo.getState();
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                dockingDataResponseVo.setMeterSerialNo(serialNo);
                dockingDataResponseVo.setFieldCode(errorCode);
                responseVoList.add(dockingDataResponseVo);
//                NetEqu equ = netEqus.stream().filter(v -> serialNo.equals(v.getSerialNo())).findFirst().orElse(null);
                CommNetEquipment commNetEquipment = repositoryService.getCommNetEquipmentByNetSerial(serialNo);
                if (null == commNetEquipment) {
                    dockingDataResponseVo.setFieldCode(objectNotExist);
                    dockingDataResponseVo.setReason("网络设备不存在");
                    continue;
                }

                Result result = new Result();
                String message = "成功";
                int code = ResultCode.SUCCESS.code;
                try {
//                    upService.updateNetData(equ, state);
                    BaseContainer.netStatusCallback().rccStatusChange(serialNo, state);
                } catch (Exception e) {
                    code = -1;
                    message = ExceptionUtils.getFullStackTrace(e);
                }
                result.setResultCode(code);
                result.setMessage(message);

                if (ResultCode.SUCCESS.code.equals(result.getResultCode())) {
                    dockingDataResponseVo.setFieldCode(successCode);
                    dockingDataResponseVo.setReason(ResultCode.SUCCESS.message);
                } else {
                    dockingDataResponseVo.setFieldCode(errorCode);
                    dockingDataResponseVo.setReason(result.getMessage());
                }
            }
        }
        return new Result<List<DockingDataResponseVo>>().handleSuccessResult(responseVoList);
    }

    @Override
    public Result<List<DockingDataResponseVo>> batchSaveStationMeterData(List<StationMeterDataDockingDataVo> stationMeterDataDockingDataVos) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(stationMeterDataDockingDataVos)) {
            for (StationMeterDataDockingDataVo stationMeterDataDockingDataVo : stationMeterDataDockingDataVos) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                CommNetEquipment commNetEquipment = repositoryService.getCommNetEquipmentByNetSerial(stationMeterDataDockingDataVo.getNetEquSerialNo());
                if (check(responseVoList, dockingDataResponseVo, commNetEquipment, stationMeterDataDockingDataVo.getNetEquSerialNo()))
                    continue;
//                List<String> collect = commNetEquipment.getCommValveList().stream().map(CommValve::getSerial).collect(Collectors.toList());
                CommMeter commMeter = repositoryService.getCommMeterByNodeSerialForNetEqu(stationMeterDataDockingDataVo.getMeterSerialNo(), commNetEquipment.getId());
                if (commMeter == null) {
                    log.error("batchSaveStationMeterData无此档案---" + JSON.toJSONString(stationMeterDataDockingDataVo));
                    dockingDataResponseVo.setNetEquSerialNo(stationMeterDataDockingDataVo.getNetEquSerialNo());
                    dockingDataResponseVo.setMeterSerialNo(stationMeterDataDockingDataVo.getMeterSerialNo());
                    dockingDataResponseVo.setFieldCode(objectNotExist);
                    dockingDataResponseVo.setReason("节点设备档案不存在");
                    responseVoList.add(dockingDataResponseVo);
                    continue;
                }
//                if (check(responseVoList, dockingDataResponseVo, collect, stationMeterDataDockingDataVo.getMeterSerialNo(), stationMeterDataDockingDataVo.getNetEquSerialNo()))
//                    continue;
                HotMeterVO currentData = new HotMeterVO();
                currentData.setMeterSerial(stationMeterDataDockingDataVo.getMeterSerialNo());
                currentData.setSuccess(stationMeterDataDockingDataVo.getState());
                if (stationMeterDataDockingDataVo.getReason()!=null)
                currentData.setFaultCode(stationMeterDataDockingDataVo.getReason());
//                currentData.setPlanTime(stationMeterDataDockingDataVo.getPlanTime());
                currentData.setReadDate(stationMeterDataDockingDataVo.getReadTime());
                currentData.setWorkTime(StringUtils.isEmpty(stationMeterDataDockingDataVo.getWorkTime()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getWorkTime()).intValue());
                currentData.setSupplyTemp(StringUtils.isEmpty(stationMeterDataDockingDataVo.getSupplyTemperature()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getSupplyTemperature()).floatValue());
                currentData.setReturnTemp(StringUtils.isEmpty(stationMeterDataDockingDataVo.getReturnTemperature()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getReturnTemperature()).floatValue());
                currentData.setAccFlow(StringUtils.isEmpty(stationMeterDataDockingDataVo.getAccFlow()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getAccFlow()).floatValue());
                currentData.setAccHeat(StringUtils.isEmpty(stationMeterDataDockingDataVo.getAccHeat()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getAccHeat()).floatValue());
                currentData.setPower(StringUtils.isEmpty(stationMeterDataDockingDataVo.getHeat()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getHeat()).floatValue());
                currentData.setFlow(StringUtils.isEmpty(stationMeterDataDockingDataVo.getFlow()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getFlow()).floatValue());
                currentData.setFlow(StringUtils.isEmpty(stationMeterDataDockingDataVo.getFlow()) ? null : new BigDecimal(stationMeterDataDockingDataVo.getFlow()).floatValue());
//                currentData.setb(StringUtils.isEmpty(stationMeterDataDockingDataVo.getBattery())? null: new BigDecimal(stationMeterDataDockingDataVo.getBattery()));
                currentData.setStatus(stationMeterDataDockingDataVo.getStateCode());
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
                asynResult.setIdentity(commMeter.getId());
//                asynResult.setSymbol("data");
                asynResult.setContent(currentData);
                MqttUtil.send(HotMeterVO.TOPIC, asynResult);
            }
        }
        return new Result<List<DockingDataResponseVo>>().handleSuccessResult(responseVoList);
    }

    @SneakyThrows
    @Override
    public Result<Integer> saveDongYingBuildValveData(List<DoYBuildValveParamVo> doYBuildValveParamVoList) {
        List<DockingDataResponseVo> responseVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(doYBuildValveParamVoList)) {
            for (DoYBuildValveParamVo doYBuildValveParamVo : doYBuildValveParamVoList) {
                DockingDataResponseVo dockingDataResponseVo = new DockingDataResponseVo();
                CommValve commValveOfDongYing = repositoryService.getCommValveOfDongYing(doYBuildValveParamVo.getBuildValveNo(), doYBuildValveParamVo.getFactoryName());
                if (commValveOfDongYing == null) {
                    return new Result<Integer>().handelResult(ResultCode.OBJECT_NOT_EXISTS.code, "楼阀不存在(厂家、楼阀编号、通讯方式)");
                }
                ValveVO buildValveCurrentData = new ValveVO();
                buildValveCurrentData.setSuccess(true);
//                buildValveCurrentData.setPlanTime(planTime);
                Date planTime = UtilTime.StringToDate(doYBuildValveParamVo.getPlanTime(), "yyyy-MM-dd HH:mm:ss");
                buildValveCurrentData.setReadTime(planTime);
                buildValveCurrentData.setValveDate(planTime);
                String actualOpening = doYBuildValveParamVo.getActualOpening();
                if (StringUtils.isNotBlank(actualOpening)) {
                    buildValveCurrentData.setActOpen(new BigDecimal(actualOpening).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
                }
                String controlOpening = doYBuildValveParamVo.getControlOpening();
//                if (StringUtils.isNotBlank(controlOpening)) {
//                    buildValveCurrentData.setControlOpening(new BigDecimal(controlOpening).setScale(2, BigDecimal.ROUND_HALF_UP));
//                }
                String returnTemperature = doYBuildValveParamVo.getReturnTemperature();
                if (StringUtils.isNotBlank(returnTemperature)) {
                    buildValveCurrentData.setReturnTemp(new BigDecimal(returnTemperature).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
                }
                buildValveCurrentData.setStatus(doYBuildValveParamVo.getStateCode());
//                buildValveCurrentData.setIsAlarm(false);
//                buildValveCurrentData.setIsFault(false);
//                buildValveCurrentData.setAlarmSettingIds(null);
//                buildValveCurrentData.setFaultTypeIds(null);
//                buildValveCurrentData.setReason(null);
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
//                asynResult.setSerial(doYBuildValveParamVo.getNetEquSerialNo());
//                asynResult.setSymbol("data");
                asynResult.setContent(buildValveCurrentData);
                MqttUtil.send(ValveVO.TOPIC, asynResult);
            }
        }
        return new Result<Integer>().handleSuccessResult(1);
    }

    private OkHttpClient httpClient;

    @Scheduled(cron = "0 0 */1 * * ?")
    public void saveXinJiangTempPanel() {
        log.info("同步新疆热总五包数据任务启动 --- {}", UtilTime.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
        if (this.httpClient == null) {
            this.httpClient = new OkHttpClient()
                    .newBuilder()
                    .callTimeout(5000, TimeUnit.MILLISECONDS)
                    .build();
        }
        try {
            Response response = httpClient.newCall(new Request.Builder().url("http://124.239.148.218:50001/DynamicApi/v_roomtemp_hfrn")
                    .post(RequestBody.create("{\"AppSecret\":\"hfrn\"}", MediaType.parse("application/json; charset=utf-8")))
                    .build()).execute();
            if (response.body() != null) {
                Map<String, Object> result = SerializeUtil.json2map(response.body().string());
                log.info("新疆热总五包数据: {}", result);
                if ((Boolean) result.get("IsSuccess")) {
                    List<Map<String, Object>> data = (List<Map<String, Object>>) result.get("Data");
                    data.forEach(map -> {
                        CommPanel commPanel = commPanelRepository.findOne(Example
                                .of(CommPanel.builder().serial((String) map.get("TEMPNUM"))
                                        .communicationType(2).build())).orElse(null);
                        if (commPanel != null) {
                            PanelVO panelVO = new PanelVO();
                            panelVO.setSerial((String) map.get("TEMPNUM"));
                            if (map.get("ROOMTEMP") != null) {
                                panelVO.setTemperature(((Double) map.get("ROOMTEMP")).floatValue());
                            }
                            if (map.get("GETTIME") != null) {
                                panelVO.setPanelDate(UtilTime.StringToDate((String) map.get("GETTIME"), "yyyy-MM-dd HH:mm:ss"));
                            }
                            AsynResult asynResult = AsynResult.success();
                            asynResult.setIdentity(commPanel.getId());
                            asynResult.setTimestamp(System.currentTimeMillis());
                            asynResult.setContent(Collections.singletonList(panelVO));
                            MqttUtil.send(PanelVO.TOPIC, asynResult);
                        }
                    });
                }
            }
        } catch (Exception e) {
            log.error("新疆热总五包数据接口异常: ", e);
        }
    }

}
